﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Resources;
using System.IO;

namespace TaxLawView
{
    /// <summary>
    /// LawBrowser.xaml 的交互逻辑
    /// </summary>
    public partial class LawBrowser : UserControl
    {
        private string _lawDoc;

        public Law Law
        {
            get { return (Law)GetValue(LawProperty); }
            set { SetValue(LawProperty, value); }
        }

        public static readonly DependencyProperty LawProperty =
            DependencyProperty.Register("Law", typeof(Law), typeof(LawBrowser), new PropertyMetadata(OnLawPropertyChanged));

        private static void OnLawPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
        {
            LawBrowser source = (LawBrowser)o;
            source.LoadLaw(e.NewValue as Law);
        }

        private void LoadLaw(Law law)
        {
            if (!browser.IsLoaded || law == null)
                return;
            string content = law.Content;
            string htmlContent = string.Format("<p>{0}</p>", law.Name);
            if (!string.IsNullOrEmpty(content))
            {
                htmlContent += content.Replace("\\r\\n", "\r\n");
            }
            browser.InvokeScript("loadContent", htmlContent);
        }


        public LawBrowser()
        {
            InitializeComponent();
            StreamResourceInfo sri = Application.GetResourceStream(new Uri("/TaxLawView;component/View/LawDoc.htm", UriKind.RelativeOrAbsolute));
            using (StreamReader sr = new StreamReader(sri.Stream))
            {
                _lawDoc = sr.ReadToEnd();
            }
            browser.NavigateToString(_lawDoc);
            browser.LoadCompleted += new LoadCompletedEventHandler(browser_LoadCompleted);
        }

        void browser_LoadCompleted(object sender, NavigationEventArgs e)
        {
            LoadLaw(Law);
        }
    }
}
